Ext.define('Admin.view.baseInfo.MapController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.mapController',
    config: {
        map: null
    },
    afterRender: function(b) {
        this.getReferences().panel.showAt(10, 120);
        this.lookupReference('layerBtn1').showAt(b.getWidth() - 180, 20);
        this.lookupReference('layerBtn2').showAt(b.getWidth() - 90, 20);
        this.lookupReference('map-legend').showAt(b.getWidth() - 130, b.getHeight() - 180);
    },
    onMapInit: function(b) {
        var me = this;
        b.on("load",
            function() {
                me.loadData();
                b.graphics.enableMouseEvents();
            });
        this.setMap(b);
        this.initMapLayer(b)
    },
    initMapLayer: function(map) {
        var d = this;
        require(["esri/request", "esri/graphic", "esri/graphicsUtils", "esri/layers/GraphicsLayer", "esri/layers/FeatureLayer", "esri/geometry/Point", "esri/geometry/Polyline", "esri/geometry/Polygon", "gis/OnlineMap", "esri/dijit/HomeButton", "dojo/_base/connect", "dojo/_base/array", "esri/layers/ArcGISTiledMapServiceLayer"],
            function(request, Graphic, b, B, t, u, w, z, A, y, a, v, ArcGISTiledMapServiceLayer) {

                //layer1: 底图  layer2影像底图
                //request esri请求方法
                //Graphic 多边形
                var layer1 = new ArcGISTiledMapServiceLayer("https://map.jxwrd.gov.cn/arcgis/rest/services/EsriBaseMap/MapServer"); //底图服务
                layer1.id = 'layer1';
                layer1.visible = true;
                map.addLayer(layer1);
                var layer2 = new ArcGISTiledMapServiceLayer("https://map.jxwrd.gov.cn/arcgis/rest/services/Image/jx2mDOM/MapServer");
                layer2.id = 'layer2';
                layer2.visible = false;
                map.addLayer(layer2);

                var D = map.infoWindow;
                map.infoWindow.resize(430, 300);
                a.connect(D, "onSelectionChange",
                    function() {
                        console.info("onSelectionChange");
                        var e = D.getSelectedFeature();
                        if (e != null) {
                            var f = echarts.init(document.getElementById("popupchart"));
                            f.setOption(d.getChartDemoOptions(e))
                        }
                    });
                request({
                    url: config.RIVER === "02" ? "resources/data/json/fhly.json" : "resources/data/json/yhly.json",
                    handleAs: "json"
                }).then(function(h) {
                        var f = [];
                        v.forEach(h.features,
                            function(k) {
                                var j = new z({
                                    rings: k.geometry.rings,
                                    spatialReference: h.spatialReference
                                });
                                var l = new Graphic(j);
                                l.setAttributes(k.attributes);
                                f.push(l)
                            });

                        var e = {
                            layerDefinition: {
                                geometryType: h.geometryType,
                                objectIdField: "OBJECTID",
                                fields: h.fields,
                                drawingInfo: {
                                    renderer: {
                                        type: "simple",
                                        label: "",
                                        description: "",
                                        symbol: mapconfig.symbols.boundary
                                    }
                                }
                            },
                            featureSet: {
                                features: f,
                                geometryType: h.geometryType
                            }
                        };

                        lyr_boundary = new t(e, {
                            id: "BDLAYER"
                        });

                        lyr_boundary.setMaxScale(200000);
                        map.addLayer(lyr_boundary, -1);
                        var g = b.graphicsExtent(f, true);
                        map.setExtent(g);
                        console.log("Success: ", lyr_boundary.id + ":数据加载成功")
                    },
                    function(e) {
                        console.log("Error: ", e.message)
                    });
            })
    },
    loadData: function() {
        this.getViewModel().getStore("pStore").load();
        this.getViewModel().getStore("zqSkStore").load();
        this.getViewModel().getStore("zqStore").load();
        this.getViewModel().getStore("wqStore").load();
    },
    stnmRenderer: function(b) {
        return this.rendererRegExp ? b.replace(this.rendererRegExp, '<span style="color:#35baf6;font-weight:bold">$1</span>') : b
    },
    swLoad: function(h, f, g, e) {
        console.log('水量站数据加载', h);

        if (g == true) {

            for (var a = 0; a < f.length; a++) {
                var K = f[a].data;
                K.stnm = K.stNm;
                K.sttp = "ZQ";
            }
            //水文站
            this.creatStationLayer(f, "LAYER_SW", mapconfig.layerDefs.sw, mapconfig.templates.sw, mapconfig.labels.sw, true)
        } else {
            console.log("加载失败");
        }
    },
    swSkLoad: function(h, f, g, e) {
        console.log(h);

        if (g == true) {

            for (var a = 0; a < f.length; a++) {
                var K = f[a].data;
                K.stnm = K.stNm;
                K.sttp = "ZQ";
            }
            //水文水库站
            this.creatStationLayer(f, "LAYER_SWSK", mapconfig.layerDefs.sw, mapconfig.templates.sw, mapconfig.labels.sw, false)
        } else {
            console.log("加载失败");
        }
    },
    ppLoad: function(h, f, g, e) {
        if (g == true) {
            for (var a = 0; a < f.length; a++) {
                var K = f[a].data;
                K.stnm = K.stNm;
                K.sttp = "PP";
            }
            //雨量站
            this.creatStationLayer(f, "LAYER_PP", mapconfig.layerDefs.pp, mapconfig.templates.pp, mapconfig.labels.pp, false)
        } else {
            console.log("雨量站加载失败\u2026\u2026")
        }
    },
    wqLoad: function(h, f, g, e) {
        if (g == true) {
            for (var a = 0; a < f.length; a++) {
                var K = f[a].data;
                K.stnm = K.stNm;
                K.sttp = "PP";
            }
            //水质站
            this.creatStationLayer(f, "LAYER_WQ", mapconfig.layerDefs.wq2, mapconfig.templates.pp, mapconfig.labels.sw, false)
        } else {
            console.log("水质站加载失败\u2026\u2026")
        }
    },
    checkLayerVisible: function(f, h) {
        var g = this.getMap();
        if (f.inputValue == 'LAYER_MAP') {
            g.getLayer('layer1').setVisibility(!h);
            g.getLayer('layer2').setVisibility(h);
        } else if (f.inputValue == 'LAYER_SW') {
            var e = g.getLayer('LAYER_SW');
            if (e) {
                e.setVisibility(h);
            }

            var e2 = g.getLayer('LAYER_SWSK');
            if (e2) {
                e2.setVisibility(h);
            }
        } else {
            var e = g.getLayer(f.inputValue);
            if (e) {
                e.setVisibility(h);
            }
        }
    },
    creatStationLayer: function(o, h, j, p, k, l) {
        var m = this.getMap();
        require(["esri/graphic", "esri/Color", "esri/InfoTemplate", "esri/layers/GraphicsLayer", "esri/layers/FeatureLayer", "esri/layers/LabelClass", "esri/symbols/SimpleMarkerSymbol", "esri/renderers/SimpleRenderer", "esri/renderers/UniqueValueRenderer", "esri/renderers/jsonUtils", "esri/geometry/Point", "esri/geometry/Polyline", "esri/geometry/Polygon", "esri/dijit/Popup", "esri/dijit/PopupTemplate"],
            function(e, g, G, c, M, T, F, I, P, R, H, d, U, O, J) {
                var b = new M({
                    layerDefinition: j,
                    featureSet: {
                        geometryType: "esriGeometryPoint",
                        features: []
                    }
                }, {
                    id: h,
                    visible: l,
                    infoTemplate: new G({
                        title: "${stnm}|${stcd}",
                        content: "<div id='popupchart' style='background-color: #00b0ff; width: 420px;height:200px;'>popupchart</div>"
                    })
                });
                var N = new T(k);
                b.setLabelingInfo([N]);
                m.addLayer(b, -1);
                var Q = [];
                for (var a = 0; a < o.length; a++) {
                    console.log('测站信息', o)
                    var K = o[a].data;
                    // console.log('K', K)

                    var S = new H({
                        x: Number(K.lgtd),
                        y: Number(K.lttd),
                        spatialReference: {
                            wkid: 4490
                        }
                    });
                    var f = new e(S, null, K);
                    K.geometry = S;
                    if (!K.lgtd || !K.lttd) {
                        console.log('没有坐标信息', K)
                        return;
                    } else {
                        console.log('有坐标信息', K)
                        Q.push(f)
                    }
                }
                b.applyEdits(Q, null, null);
                // console.log("Success: ", h + ":数据加载成功")
            });
    },
    gridItemClick: function(q, k, p, e, m, r) {
        var l = k.data;
        if (!l.lgtd || !l.lttd) {
            Ext.Msg.alert('系统提示!', l.stNm + '没有坐标信息!!!')
        } else {
            var o = this.getMap();
            o.centerAndZoom(l.geometry, 12)
        }
    },
    onBtnMenuClick: function(j, l, k, m) {
        var e = this.getReferences().btnType;
        e.setText(l.text);
        var h = l.view;
        if (h) {
            this.setCurrentView(h, l.params)
        }
    },
    setCurrentView: function(e, f) {
        var d = this.getReferences().panel;
        Ext.suspendLayouts();
        d.removeAll(true);
        d.add(Ext.apply({
                xtype: e
            },
            f));
        Ext.resumeLayouts(true)
    },
    stnmRenderer: function(b) {
        return this.rendererRegExp ? b.replace(this.rendererRegExp, '<span style="color:#35baf6;font-weight:bold">$1</span>') : b
    },
    onSearchFieldChange: function(j, k) {
        var l = this,
            h = l.getReferences().panel,
            m = h.items.first(),
            g = m.getStore();
        if (k) {
            l.rendererRegExp = new RegExp("(" + k + ")", "gi");
            j.getTrigger("clear").show();
            l.filterStore(g, k)
        } else {
            l.rendererRegExp = null;
            g.clearFilter();
            j.getTrigger("clear").hide()
        }
    },
    doGridFilter: function(c) {
        var d = this.getReferences().searchField;
        this.onSearchFieldChange(d, d.getValue())
    },
    clearGridFilter: function(b) {
        this.getReferences().searchField.setValue()
    },
    filterStore: function(d, c) {
        if (c.length < 1) {
            d.clearFilter()
        } else {
            d.getFilters().replaceAll({
                property: "stnm",
                value: new RegExp(Ext.String.escapeRegex(c), "i")
            })
        }
    },
    getChartDemoOptions: function(N) {
        var Q = new Date();
        var p = [];
        var M = [];
        var I = [];
        var K = [];
        var o = [];
        var P = [];
        var z = [];
        var O = [];
        var k = [];
        for (i = 0; i < 24; i++) {
            var F = Ext.Date.add(Q, Ext.Date.HOUR, -1 * i);
            p.push(Ext.Date.format(F, "m-d\nH:00"));
            var J = Ext.util.Format.number(Math.random() * 10 + 16, "0.00");
            var D = Ext.util.Format.number(Math.random() * 100, "0.00");
            I.push(J);
            K.push(D)
        }
        for (i = 0; i < 15; i++) {
            var F = Ext.Date.add(Q, Ext.Date.DAY, -1 * i);
            M.push(Ext.Date.format(F, "m-d"));
            var G = Ext.util.Format.number(Math.random() * 4 + 6, "0.0");
            var E = Ext.util.Format.number(Math.random() * 2 + 6, "0.0");
            var C = Ext.util.Format.number(Math.random() * 3 + 8, "0.0");
            var t = Ext.util.Format.number(Math.random() * +1, "0.0");
            var B = Ext.util.Format.number(Math.random(), "0.0");
            o.push(G);
            P.push(E);
            z.push(C);
            k.push(B);
            O.push(t)
        }
        var H = {
            title: {
                show: true,
                text: N.attributes.stnm + "站24小时水位过程线",
                left: "center",
                padding: [0, 0]
            },
            grid: {
                left: "40",
                right: "20",
                top: "30",
                bottom: "35",
                containLabel: false
            },
            tooltip: {
                trigger: "axis"
            },
            xAxis: {
                data: p.reverse()
            },
            yAxis: [{
                type: "value",
                name: "水位",
                min: 15,
                max: 30,
                interval: 5,
                axisLabel: {
                    formatter: "{value} m"
                }
            }],
            series: [{
                name: "水位",
                type: "line",
                data: I,
                itemStyle: {
                    normal: {
                        color: "#0000FF"
                    }
                },
                markPoint: {
                    data: [{
                        name: "",
                        xAxis: p[23],
                        yAxis: I[23]
                    }]
                },
                markLine: {
                    label: {
                        normal: {
                            position: "middle",
                            formatter: "警戒水位26.2m"
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: "#FF0000"
                        }
                    },
                    data: [{
                        name: "起始",
                        xAxis: 0,
                        yAxis: 28.6
                    }]
                }
            }]
        };
        if (N.attributes.sttp == "PP") {
            H.title.text = N.attributes.stnm + "站24小时降水柱状图";
            H.yAxis = [{
                type: "value",
                name: "雨量（毫米）",
                axisLabel: {
                    formatter: "{value}"
                }
            }];
            H.series = [{
                name: "雨量",
                type: "bar",
                data: K
            }]
        } else {
            if (N.attributes.sttp == "WQ") {
                H.title.text = N.attributes.stnm + "水质过程线";
                H.xAxis = {
                    data: M.reverse()
                };
                H.yAxis = [{
                    type: "value",
                    name: "",
                    axisLabel: {
                        formatter: "{value}"
                    }
                }];
                H.legend = {
                    bottom: -5,
                    data: ["水温", "PH值", "溶解氧", "高锰酸盐指数", "氨氮"]
                };
                H.series = [{
                        name: "水温",
                        type: "line",
                        data: o
                    },
                    {
                        name: "PH值",
                        type: "line",
                        data: P
                    },
                    {
                        name: "溶解氧",
                        type: "line",
                        data: z
                    },
                    {
                        name: "氨氮",
                        type: "line",
                        data: k
                    },
                    {
                        name: "高锰酸盐指数",
                        type: "line",
                        data: O
                    }
                ]
            }
        }
        return H;
    },
    addListenerLayer1: function(me, width, height, eOpts) {
        var _that = this;
        me.getEl().dom.onclick = function() {
            var map = _that.getMap();
            var layer2 = _that.lookupReference('layerBtn2');
            me.setStyle({ border: '3px solid #f00' });
            layer2.setStyle({ border: '3px solid #ccc' })
            map.getLayer('layer1').setVisibility(true);
            map.getLayer('layer2').setVisibility(false);
        }
    },
    addListenerLayer2: function(me, width, height, eOpts) {
        var _that = this;
        me.getEl().dom.onclick = function() {
            var map = _that.getMap();
            var layer1 = _that.lookupReference('layerBtn1');
            me.setStyle({ border: '3px solid #f00' });
            layer1.setStyle({ border: '3px solid #ccc' })
            map.getLayer('layer2').setVisibility(true);
            map.getLayer('layer1').setVisibility(false);
        }
    },
    PPLayerChange: function(me, newValue, oldValue, eOpts) {
        console.log('雨量站')
        var layer = this.getMap().getLayer('LAYER_PP');
        if (layer) {
            layer.setVisibility(newValue);
        }
    },
    SWLayerChange: function(me, newValue, oldValue, eOpts) {
        var layer1 = this.getMap().getLayer('LAYER_SW');
        var layer2 = this.getMap().getLayer('LAYER_SWSK');
        if (layer1) {
            layer1.setVisibility(newValue);
        }
        if (layer2) {
            layer2.setVisibility(newValue);
        }
    },
    WQLayerChange: function(me, newValue, oldValue, eOpts) {
        var layer = this.getMap().getLayer('LAYER_WQ');
        if (layer) {
            layer.setVisibility(newValue);
        }
    },
    BDLayerChange: function(me, newValue, oldValue, eOpts) {
        var layer = this.getMap().getLayer('BDLAYER');
        if (layer) {
            layer.setVisibility(newValue);
        }
    },
});